package com.compass.doctor.ui.mine

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnUsefulButtonClick
import com.compass.doctor.databinding.ActivityUsefulListBinding
import com.compass.doctor.dialog.USEFUL_OPT_ADD
import com.compass.doctor.dialog.UsefulExpressionsDialog
import com.compass.doctor.ui.mine.adapter.UsefulExpressionsAdapter
import com.compass.doctor.ui.mine.viewmodel.UsefulExpressionsViewModel
import com.compass.framework.constant.KEY_IS_SYSTEM_USEFUL
import com.compass.framework.constant.KEY_USEFUL_CATE
import com.compass.framework.constant.KEY_USEFUL_CATE_NAME
import com.compass.framework.constant.REFRESH_USEFUL
import com.compass.framework.constant.REFRESH_USEFUL_CATE
import com.compass.framework.constant.REFRESH_USEFUL_CATE_COUNT
import com.compass.framework.constant.UsefulTypeOpeEnum
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.divider
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.model.UsefulExpressions
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getColorFromResource
import com.compass.framework.utils.getStringFromResource
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * 常用语分类页面
 */
class UsefulExpressionsListActivity : BaseVBActivity<ActivityUsefulListBinding>(),
    OnLoadMoreListener,
    OnRefreshListener {

    companion object {
        fun start(context: Context,cateId:String,cateName:String,systemUseful:Boolean) {

            val intent = Intent(context, UsefulExpressionsListActivity::class.java)
            intent.putExtra(KEY_USEFUL_CATE,cateId)
            intent.putExtra(KEY_USEFUL_CATE_NAME,cateName)
            intent.putExtra(KEY_IS_SYSTEM_USEFUL,systemUseful)
            context.startActivity(intent)
        }
    }
    private lateinit var mUsefulExpressionsAdapter: UsefulExpressionsAdapter
    private val mUsefulExpressionsViewModel: UsefulExpressionsViewModel  by viewModels()
    private var mPage :Int = 1

    private var mUsefulCateId: String? = ""
    private var mSystemUseful : Boolean? = false
    private var mCateName :String? = ""

    override fun initView(savedInstanceState: Bundle?) {
        mUsefulCateId=intent.getStringExtra(KEY_USEFUL_CATE)
        mSystemUseful = intent.getBooleanExtra(KEY_IS_SYSTEM_USEFUL,false)
        mCateName = intent.getStringExtra(KEY_USEFUL_CATE_NAME)
        if(!mCateName.isNullOrEmpty()){
            mBinding.tvTitleBar.setMiddleText(mCateName)
        }
        mBinding.tvTitleBar.getRightTextView().visible()
        mBinding.tvTitleBar.setRightText("编辑")
        mBinding.tvTitleBar.onClick {
           if(mUsefulExpressionsAdapter.getmType() == UsefulTypeOpeEnum.LIST){
               mUsefulExpressionsAdapter.setmType(UsefulTypeOpeEnum.DELETE)
               mBinding.tvTitleBar.setRightText("取消")
               mBinding.tvAddExpression.text = "确认删除"
           }else{
               mUsefulExpressionsAdapter.setmType(UsefulTypeOpeEnum.LIST)
               mBinding.tvTitleBar.setRightText("编辑")
               mBinding.tvAddExpression.text = "添加常用语"
           }
        }

        mBinding.llAddExpression.onClick {
            if(mUsefulExpressionsAdapter.getmType() == UsefulTypeOpeEnum.LIST){
                //显示添加分组的dialog
                UsefulExpressionsDialog.Builder(this, USEFUL_OPT_ADD,onUsefulButtonClick).show()
            }else{
                //删除当前选中的常用语
                if(checkData()){
                    CommonMessageDialog.Builder(this@UsefulExpressionsListActivity)
                        .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
                        .setMessage("是否删除选中的常用语？")
                        .setConfirm(getStringFromResource(R.string.default_confirm))
                        .setCancel(getString(com.compass.framework.R.string.default_cancel))
                        .setonCancelListener {
                            it?.dismiss()
                        }
                        .setonConfirmListener {
                            mUsefulExpressionsViewModel.delUsefulExpressions(mUsefulExpressionsAdapter.getChooseCateIds())
                            it?.dismiss()
                        }.create().show()

                }else{
                    showToast("请先选择常用语分组")
                }
            }
        }

        mUsefulExpressionsViewModel.usefulExpressionsLiveData.observe(this){
            dismissLoading()
            if(mPage == 1){
                //第一页数据返回
                mUsefulExpressionsAdapter.setData(it)
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding.emptyView.visible()
//                    mBinding.rvGroup.gone()
                } else {
                    mBinding.emptyView.gone()
//                    mBinding.rvGroup.visible()
                }
            }else{
                mBinding.refreshLayout.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    mUsefulExpressionsAdapter.addAll(it)
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            }
        }

        mUsefulExpressionsViewModel.addUsefulExpressionsData.observe(this){
            dismissLoading()
            if(it!=null){
                mPage = 1
                getUsefulListData()
                //通知上一个页面刷新分类列表数据
                LiveDataBus.get().with(REFRESH_USEFUL_CATE_COUNT).postValue(REFRESH_USEFUL_CATE_COUNT)
                LiveDataBus.get().with(REFRESH_USEFUL).postValue(mUsefulCateId)
            }
        }

        mUsefulExpressionsViewModel.delUsefulExpressions.observe(this){
            dismissLoading()
            if(it){
                mPage = 1
                getUsefulListData()
            }
            LiveDataBus.get().with(REFRESH_USEFUL).postValue(mUsefulCateId)
            LiveDataBus.get().with(REFRESH_USEFUL_CATE_COUNT).postValue(REFRESH_USEFUL_CATE_COUNT)
        }
        initRecyclerView()
    }

    /**
     * 校验数据
     */
    private fun checkData():Boolean{
        val ids = mUsefulExpressionsAdapter.getChooseCateIds()
        return ids.isNotEmpty()
    }

    private var onUsefulButtonClick = object : OnUsefulButtonClick {
        override fun onAddButton(content: String, type: Int) {
            super.onAddButton(content, type)
            if (type == 1){
                //添加常用语分组
                showLoading()
                mUsefulExpressionsViewModel.addUsefulExpressionCate(content)
            }else{
                showLoading()
                //添加常用语
                mUsefulCateId?.let { mUsefulExpressionsViewModel.addUsefulExpression(it,content) }
            }
        }
    }

    private fun initRecyclerView(){
        mUsefulExpressionsAdapter = UsefulExpressionsAdapter()
        mUsefulExpressionsAdapter.onItemClickListener = { _, position ->
            if(mUsefulExpressionsAdapter.getmType() != UsefulTypeOpeEnum.LIST){
                val list: MutableList<UsefulExpressions>? =  mUsefulExpressionsViewModel.usefulExpressionsLiveData.value;
                list?.forEachIndexed { index, item ->
                    if(index == position){
                        item.selectStatus = !item.selectStatus
                    }
                }
                mUsefulExpressionsViewModel.usefulExpressionsLiveData.postValue(list)
            }
        }

        mBinding.refreshLayout.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@UsefulExpressionsListActivity)
            setOnLoadMoreListener(this@UsefulExpressionsListActivity)
        }

        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            divider(getColorFromResource(R.color.color_d6d6d6), dpToPx(1), false)
            addItemDecoration(NormalItemDecoration().apply {
                setBounds(top = dpToPx(10), left = dpToPx(10), right = dpToPx(10), bottom = dpToPx(10))
            })
            adapter = mUsefulExpressionsAdapter
        }
    }


    override fun initData() {
        super.initData()
        getUsefulListData()
    }

    private fun getUsefulListData(){
        showLoading()
        mSystemUseful?.let { mUsefulCateId?.let { it1 ->
            mUsefulExpressionsViewModel.getUsefulExpressionsListByCate(it,
                it1,mPage)
        } }
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getUsefulListData()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getUsefulListData()
    }

}